package com.hcbd.tdwt.ui.haige.common.fragment;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.location.LocationManager;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RadioButton;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.recyclerview.widget.GridLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.hcbd.tdwt.R;
import com.hcbd.tdwt.base.bd.BDNotificationManager;

import com.hcbd.tdwt.ui.haige.common.adapter.SecurityContentAdapter;
import com.hcbd.tdwt.ui.haige.common.vo.SecurityContentVO;
import com.hcbd.tdwt.MainApp;

import com.hcbd.tdwt.base.BaseFragment;
import com.hcbd.tdwt.base.BeidouBoxParams;
import com.hcbd.tdwt.base.Constant;
import com.hcbd.tdwt.base.ConvertToBdMsgTool;
import com.hcbd.tdwt.base.GlobalParams;
import com.hcbd.tdwt.util.DateUtils;
import com.hcbd.tdwt.util.SharedPreferencesUtil;
import com.hcbd.tdwt.util.StringUtil;
import com.hcbd.tdwt.view.MultiLineRadioGroup;
import com.pangu.bdsdk2021.entity.terminalthree.BDSnrInfo;
import com.raizlabs.android.dbflow.sql.language.SQLite;
import com.hcbd.tdwt.ui.xingyu.dialog.CustomDialog;
import com.hcbd.tdwt.ui.xingyu.vo.Position;


import org.androidannotations.annotations.AfterViews;
import org.androidannotations.annotations.Click;
import org.androidannotations.annotations.EFragment;
import org.androidannotations.annotations.OnActivityResult;
import org.androidannotations.annotations.ViewById;
import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.text.MessageFormat;
import java.util.List;
import java.util.Objects;

import static com.hcbd.tdwt.base.GlobalParams.sendBeidouMsgSignalEnable;

@SuppressLint("NonConstantResourceId")
@EFragment(R.layout.fragment_sos_haige)
public class SosFragment extends BaseFragment implements MainApp.LocationInfoInterface{
    @ViewById
    ImageButton headLeft;
    @ViewById
    TextView sos_tv,peace_tv;
    @ViewById
    View sos_line,peace_line;
    @ViewById
    LinearLayout sosArea,reportPeaceArea;
/*    @ViewById
    RadioGroup contentRG;*/
    @ViewById
    RecyclerView contentRv;
    @ViewById
    MultiLineRadioGroup urgentRG, healthStatusRG;
    @ViewById
    EditText phoneNum;
    @ViewById(R.id.cut_img)
    ImageView cutImg;
    @ViewById(R.id.add_img)
    ImageView addImg;
    @ViewById(R.id.people_num_tv)
    TextView peopleNumTv;
    @ViewById
    Button sendBtn;
    @ViewById(R.id.position_info)
    TextView positionInfo;
    @ViewById
    RadioButton emergency_1, healthStatus_1;
    //人数
    private int num = 1;
    public String emergencyStatus = "00";
    public String healthStatus = "00";
    Drawable lineColorDrawable;
    Drawable lightBlueDrawable;
    Drawable dividerDrawable;
    SharedPreferencesUtil sp;
    CustomDialog customDialog;
    private SecurityContentAdapter securityContentAdapter;
    private List<SecurityContentVO>list;
    private SecurityContentVO currSecurityVO;
    @AfterViews
    protected void init() {
        headLeft.setVisibility(View.GONE);
        urgentRG.setOnCheckedChangeListener((radioGroup, i) -> selectEmergencyRadioBtn());
        healthStatusRG.setOnCheckedChangeListener((radioGroup, i) -> selectHealthStatusRadioBtn());
        lineColorDrawable=getResources().getDrawable(R.drawable.button_gray_bg);
        lightBlueDrawable=getResources().getDrawable(R.drawable.btn_blue_400_click_bg);
        dividerDrawable= ContextCompat.getDrawable(this.getContext(),R.drawable.radio_divider);
        sp=new SharedPreferencesUtil(this.getContext());
        String lastNumber = sp.getAttribute(Constant.LAST_SOS_NUMBER);
        if (!TextUtils.isEmpty(lastNumber)) {
            phoneNum.setText(lastNumber);
        }
        initGPS();
        emergency_1.setChecked(true);
        healthStatus_1.setChecked(true);
        positionInfo.setText(MessageFormat.format("经度:{0}纬度:{1}高度:{2}", BeidouBoxParams.gpsLongitude, BeidouBoxParams.gpsLatitude, BeidouBoxParams.gpsAltitude));
        isRefreshing=true;
        initMsgRegister();
        sosLL();
        customDialog=new CustomDialog(this.getContext(), "添加自定义内容", CustomDialog.ADD_DIALOG, (dialog, content, view) -> {
            try {
                if("".equals(content)){
                    toast("请输入内容");
                    return;
                }
                SecurityContentVO contentVO=new SecurityContentVO();
                contentVO.content=content;
                contentVO.isSelect=false;
                contentVO.insert();
                list=SQLite.select().from(SecurityContentVO.class).queryList();
                initPeaceContent();
                for(SecurityContentVO securityContentVO:list){
                    if(securityContentVO.isSelect){
                        currSecurityVO=securityContentVO;
                        break;
                    }
                }
                hideSoftInput(view);
                dialog.dismiss();
            }catch (Exception e){
                e.printStackTrace();
            }
        });
        customDialog.setOkBtnStyle(getContext().getDrawable(R.color.blue_400), getContext().getColor(R.color.white));
        customDialog.setQuiteBtnStyle(getContext().getDrawable(R.color.gray_600),getContext().getColor(R.color.white));
        list=SQLite.select().from(SecurityContentVO.class).queryList();
        for(SecurityContentVO securityContentVO:list){
            if(securityContentVO.isSelect){
                currSecurityVO=securityContentVO;
                break;
            }
        }
    }
    public void initAdapter(){
        if(securityContentAdapter==null){
            securityContentAdapter=new SecurityContentAdapter(this.getContext(),list);
            securityContentAdapter.setHasStableIds(true);
        }else{
            securityContentAdapter.notifyDataSetChanged(list);
            return;
        }
        GridLayoutManager gridLayoutManager = new GridLayoutManager(this.getContext(), 1);
        contentRv.setLayoutManager(gridLayoutManager);
        contentRv.setAdapter(securityContentAdapter);
        securityContentAdapter.setOnItemClickListener(new SecurityContentAdapter.OnItemClickListener() {
            @Override
            public void selectIndex(SecurityContentVO securityContentVO) {
                if(currSecurityVO!=null){
                    currSecurityVO.isSelect=false;
                    currSecurityVO.update();
                }
                securityContentVO.isSelect=true;
                securityContentVO.update();
                initAdapter();
                currSecurityVO=securityContentVO;
            }

            @Override
            public void delete(SecurityContentVO securityContentVO) {
                if(securityContentVO.isSelect){
                    currSecurityVO=null;
                }
                securityContentVO.delete();
                list=SQLite.select().from(SecurityContentVO.class).queryList();
                initPeaceContent();
            }
        });
    }
    public void initPeaceContent(){

        if(list.size()==0){
            SecurityContentVO contentVO1=new SecurityContentVO();
            contentVO1.content="我已安全到达";
            contentVO1.isSelect=true;
            contentVO1.insert();
            currSecurityVO=contentVO1;
            SecurityContentVO contentVO2=new SecurityContentVO();
            contentVO2.content="谢谢大家关心，已平安归来";
            contentVO2.insert();
            list.add(contentVO1);
            list.add(contentVO2);
        }
        initAdapter();
    }
   /* public void addRadioButton(String content){
        RadioButton radioButton=new RadioButton(this.getContext());
        radioButton.setText(content);
        radioButton.setButtonDrawable(null);
        radioButton.setGravity(Gravity.CENTER);
        radioButton.setPadding(0,30,0,0);
        radioButton.setLayoutParams(layoutParams);
        radioButton.setCompoundDrawablePadding(30);
        radioButton.setCompoundDrawablesWithIntrinsicBounds(null, null, null, dividerDrawable);
        radioButton.setTextColor(ContextCompat.getColorStateList(this.getContext(),R.color.rb_select_color_black_blue_400));
        contentRG.addView(radioButton);
    }*/
    @Click
    void customTv(){
        CustomDialog.show(customDialog);
    }

    @Click
    void sosLL(){
        sos_tv.setTextSize(16);
        peace_tv.setTextSize(12);
        sos_line.setVisibility(View.VISIBLE);
        peace_line.setVisibility(View.GONE);
        sosArea.setVisibility(View.VISIBLE);
        reportPeaceArea.setVisibility(View.GONE);
    }
    @Click
    void reportPeaceLL(){
        sos_tv.setTextSize(12);
        peace_tv.setTextSize(16);
        sos_line.setVisibility(View.GONE);
        peace_line.setVisibility(View.VISIBLE);
        sosArea.setVisibility(View.GONE);
        reportPeaceArea.setVisibility(View.VISIBLE);
        initPeaceContent();
    }
    //选择联系人按钮,从手机通讯录添加联系人
    @Click(R.id.choose_contact_img)
    void chooseContactImg(){
        openContacts();
    }
    @Click
    void cutImg() {
        //减号
        if (num > 1) {
            num--;
            peopleNumTv.setText(String.valueOf(num));
        }
    }

    @Click
    void addImg() {
        //加号
        if (num < 255) {
            num++;
            peopleNumTv.setText(String.valueOf(num));
        }
    }
    void selectEmergencyRadioBtn() {
        RadioButton rb = Objects.requireNonNull(this.getActivity()).findViewById(urgentRG.getCheckedRadioButtonId());
        emergencyStatus = rb.getTag().toString();
    }
    void selectHealthStatusRadioBtn() {
        RadioButton rb = Objects.requireNonNull(this.getActivity()).findViewById(healthStatusRG.getCheckedRadioButtonId());
        String tag = rb.getTag().toString();
        healthStatus = tag;
    }
    @Click
    void sendBtn(){
        String phone = getTextStr(phoneNum);


        if (TextUtils.isEmpty(phone)) {
            toast("联系人号码不能为空");
            return;
        }
        if (phone.length() != 11) {
            toast("联系人号码格式不对");
            return;
        }
        if (!StringUtil.isMobilePhone(phone)) {
            toast("联系人号码格式不对");
            return;
        }
        Position position = new Position();
        position.setLongitude(GlobalParams.gpsLongitude);
        position.setLatitude(GlobalParams.gpsLatitude);
        position.setAltitude(GlobalParams.gpsAltitude);
        position.setTime(Long.parseLong(DateUtils.getTimeStamp()));
        if (BeidouBoxParams.isBoxConnectNormal) {
            if(sosArea.getVisibility()==View.VISIBLE){//发送SOS消息
                sendSosMsg(phone, position, emergencyStatus, healthStatus, num);
            }else{
                if(currSecurityVO==null){
                    toast("请选择要发送的信息!");
                    return;
                }
                sendSecurityMsg(phone,currSecurityVO.content,position);
            }
        } else {
            toast("请连接终端！");
        }

    }
    /**
     * 通过北斗网发送
     *
     */
    private void sendSosMsg(String phone, Position position, String situation,  String healthStatus, int num) {
        int beidouSignal = BeidouBoxParams.getBdSignal();
        if (beidouSignal < sendBeidouMsgSignalEnable) {
            toast("信号不好，请移动终端位置");
            return;
        }
        String content= ConvertToBdMsgTool.castUserMessageTo0x13(phone, position, situation, healthStatus, num);

        BDNotificationManager.getInstance().CCTCQ(GlobalParams.rdCentreNumber,2,2,content);
        //最后一次发送的号码
        sp.addAttribute(Constant.LAST_SOS_NUMBER, phone);
        // 发送状态倒计时线程
        MainApp.getInstance().startNewSentWaitSecTimer();
        toast("发送成功");
    }
    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(BDSnrInfo bdSnrInfo){
        if(BeidouBoxParams.sentWaitSec > 0){
            return;
        }
        refreshStatus();
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(String bleContent){
        if("onConnectError".equals(bleContent)){
            noConBtn();
        }
    }
    @OnActivityResult(Constant.GET_MAIL_LIST_CONTACT_RESULT)
    public void getContactResult(int resultCode, Intent data){
        if (resultCode == Activity.RESULT_OK) {
            if (data != null) {
                phoneNum.setText(getPhoneNum(data));
            }
        }
    }
    @OnActivityResult(Constant.TO_OPEN_GPS_REQUEST_CODE)
    public void toOpenGpsRequestCode(int resultCode){
        if (resultCode == Activity.RESULT_OK) {
            MainApp.getInstance().initMap();
        }
    }


    /**
     * 刷新终端信息
     */
    private void refreshStatus() {
        if(!isRefreshing){
            return;
        }
        int bdSignal = BeidouBoxParams.getBdSignal();
        if(BeidouBoxParams.isBoxConnectNormal) {
            if (BeidouBoxParams.sentWaitSec > 0) {
                sendBtn.setClickable(false);
                sendBtn.setText(MessageFormat.format("{0}S", BeidouBoxParams.sentWaitSec));
                sendBtn.setBackground(lineColorDrawable);
            } else if (bdSignal < sendBeidouMsgSignalEnable) {
                sendBtn.setClickable(false);
                sendBtn.setText("没信号");
                sendBtn.setBackground(lineColorDrawable);
            } else {
                sendBtn.setClickable(true);
                sendBtn.setText("发送");
                sendBtn.setBackground(lightBlueDrawable);
            }
        }else {
            noConBtn();
        }
    }


    private void initGPS() {
        LocationManager locationManager = (LocationManager) this.getActivity().getSystemService(Context.LOCATION_SERVICE);
        if (!locationManager.isProviderEnabled(LocationManager.GPS_PROVIDER)) {
            toast("请开启手机定位!");
        }else {
            MainApp.getInstance().initMap();
        }
    }
    /**
     * 刷新UI
     */
    @SuppressLint("HandlerLeak")
    private final Handler adapterHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            if(positionInfo==null){
                return;
            }
            if (msg.what == REFRESH_STATUS_CODE) {
                refreshStatus();
            }else if(msg.what == REFRESH_LOCATION_INFO_CODE){
                if ("".equals(BeidouBoxParams.gpsLongitude) ||"".equals(BeidouBoxParams.gpsLatitude)) {
                    positionInfo.setText("未知");
                } else {
                    positionInfo.setText(MessageFormat.format("经度:{0}纬度:{1}高度:{2}", BeidouBoxParams.gpsLongitude, BeidouBoxParams.gpsLatitude, BeidouBoxParams.gpsAltitude));
                }
            }
        }
    };


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        isRefreshing = false;
    }
    private final int REFRESH_STATUS_CODE=5;
    private final int REFRESH_LOCATION_INFO_CODE=6;
    private boolean isRefreshing = false;
    @Override
    public void LocationInfo() {
        Message msg = new Message();
        msg.what = REFRESH_LOCATION_INFO_CODE;
        adapterHandler.sendMessage(msg);
    }
    public void noConBtn(){
        sendBtn.setClickable(false);
        sendBtn.setText("未连接！");
        sendBtn.setBackground(lineColorDrawable);
    }

    @Override
    public void onSwitch(){
        if(positionInfo!=null){
            positionInfo.setText(MessageFormat.format("经度:{0}纬度:{1}高度:{2}", BeidouBoxParams.gpsLongitude, BeidouBoxParams.gpsLatitude, BeidouBoxParams.gpsAltitude));

        }
        MainApp.getInstance().setLocationInfoInterface(this);
    }

    @Override
    public void  onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if(hidden){
            //不可见
            hideInputKeyBord();
            EventBus.getDefault().unregister(this);
        }else{
            Message msg = new Message();
            msg.what = REFRESH_STATUS_CODE;
            adapterHandler.sendMessage(msg);
            EventBus.getDefault().register(this);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN, sticky = true, priority = 2)
    public void eventBus(Integer delaySeconds){
        Message msg = new Message();
        msg.what = REFRESH_STATUS_CODE;
        adapterHandler.sendMessage(msg);
    }
    /**
     * 通过北斗网发送
     */
    private void sendSecurityMsg(String phone,String content, Position position) {
        int signal = BeidouBoxParams.getBdSignal();
        if (signal < sendBeidouMsgSignalEnable) {
            toast("信号不好，请移动终端位置");
            return;
        };
        String bdContent = ConvertToBdMsgTool.castUserMessageTo0x14(phone,content,position);
        BDNotificationManager.getInstance().CCTCQ(GlobalParams.rdCentreNumber,2,2,bdContent);
        //最后一次发送的号码
        sp.addAttribute(Constant.LAST_REPORT_PEACE_NUMBER, phone);
        // 发送状态倒计时线程
        MainApp.getInstance().startNewSentWaitSecTimer();
        toast("发送成功");
    }
}
